package com.financing.platform.service.impl;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.financing.platform.common.BizEnums.BiddingReceiptEnums;
import com.financing.platform.dao.IFpBiddingReceiptDao;
import com.financing.platform.dao.IJpushMessageDao;
import com.financing.platform.dao.IMessageSmsDao;
import com.financing.platform.dto.FaNoticeDTO;
import com.financing.platform.dto.FpBiddingReceiptDTO;
import com.financing.platform.dto.FpBiddingRevenueDTO;
import com.financing.platform.dto.MessageJpushDTO;
import com.financing.platform.dto.MessageJpushUserPhoneAliasDTO;
import com.financing.platform.dto.MessageSmsDTO;
import com.financing.platform.service.IFaNoticeService;
import com.financing.platform.service.IFpBiddingReceiptService;
import com.financing.platform.util.Dict;
import com.financing.platform.util.SequenceManagerNew;
import com.financing.platform.vo.FpBiddingReceiptVO;

import cn.jpush.api.utils.Base64;



@Service("fpBiddingReceiptServiceImpl")
public class FpBiddingReceiptServiceImpl implements IFpBiddingReceiptService{
	
	protected Logger log = Logger.getLogger(FpBiddingReceiptServiceImpl.class);
	String tel="400-855-8085";

	@Autowired
	IFaNoticeService faNoticeService;
	
	@Autowired
	IFpBiddingReceiptDao fpBiddingReceiptDao;
	@Autowired
	IMessageSmsDao messageSmsDaoImpl;
	
	@Autowired
	private IJpushMessageDao jpushMessageDaoImpl;
	
	@Value("#{settings['jiGuangPushRedrictYouDanNotice']}")
	private String jpushRedrict;
	
	@Override
	public Integer addFpBiddingReceipt(FpBiddingReceiptDTO dto) throws SQLException {
		return fpBiddingReceiptDao.addFpBiddingReceipt(dto);
	}
	@Override
	public Integer addFpBiddingRevenue(FpBiddingRevenueDTO dto) throws SQLException {
		return fpBiddingReceiptDao.addFpBiddingRevenue(dto);
	}
	

	@Override
	public List<FpBiddingReceiptVO> queryFpBiddingReceipt(
			FpBiddingReceiptDTO dto) throws SQLException {
		return fpBiddingReceiptDao.queryFpBiddingReceipt(dto);
	}


	@Override
	public int queryFpBiddingReceiptCount(FpBiddingReceiptDTO dto)
			throws SQLException {
		return fpBiddingReceiptDao.queryFpBiddingReceiptCount(dto);
	}


	@Override
	public Map<String, Object> queryFpBiddingReceiptDetail(
			FpBiddingReceiptDTO dto) throws SQLException {
		 Map<String, Object> queryFpBiddingReceiptDetail = fpBiddingReceiptDao.queryFpBiddingReceiptDetail(dto);
		 //收益竞价列表
		 List<Map<String, Object>> queryFpBiddingRevenueList = fpBiddingReceiptDao.queryFpBiddingRevenueList(dto.getId());
		 queryFpBiddingReceiptDetail.put("revenueList", queryFpBiddingRevenueList);
		 return queryFpBiddingReceiptDetail;
	}


	@Override
	@Transactional(rollbackFor=Exception.class)
	public int updateBiddingReceipt(FpBiddingReceiptDTO dto,Map<String, Object> currentBidding)
			throws Exception {
		//登录名
		String loginName=(String) currentBidding.get("loginName");
		//用户名称
		String uName=(String) currentBidding.get("uName");
		//手机号
		String mobile=(String) currentBidding.get("uMobile");
		int pId=Integer.parseInt(currentBidding.get("pId")+"");
		
		FaNoticeDTO faNotice=new FaNoticeDTO();
		faNotice.setCreateBy(dto.getUpdateBy());
		faNotice.setUpdateBy(dto.getUpdateBy());
		faNotice.setType("09");//消息通知
		faNotice.setProductId(pId);
		faNotice.setProductType(currentBidding.get("pType")+"");
		faNotice.setProductCode(currentBidding.get("pCode")+"");
		faNotice.setSource("【SFA】");
		faNotice.setStatus("01");
		

		MessageSmsDTO messageSmsDTO=new MessageSmsDTO();
		//添加短信息
		messageSmsDTO.setCreateBy(dto.getUpdateBy());
		messageSmsDTO.setUpdateBy(dto.getUpdateBy());
		messageSmsDTO.setCreateDate(new Date());
		messageSmsDTO.setUpdateDate(new Date());
		messageSmsDTO.setFpSmsSendType(Dict.message_type_now);
		messageSmsDTO.setStatus(Dict.status_normal);
		messageSmsDTO.setFpSmsSendStatus(Dict.message_status_not_send);
		messageSmsDTO.setFpSmsType("smsSendSwitch");
		
		String biddingStatus=dto.getBiddingStatus();
		//审核通过
	   if(BiddingReceiptEnums.BIDDING_STATUS_CG.equalsIgnoreCase(biddingStatus)){
			// 查询是否有历史承销  
			FpBiddingReceiptDTO fprdto=new FpBiddingReceiptDTO();
			fprdto.setpId(pId);
			Map<String, Object> queryBiddingReceiptSuccess =queryBiddingReceiptSuccess(fprdto);
			
			if(queryBiddingReceiptSuccess==null||queryBiddingReceiptSuccess.isEmpty()){
				//没有竞价成功的用户   不处理
			}else{
				// 给历史承销成功的  置为失效
				fprdto.setId(Integer.parseInt(queryBiddingReceiptSuccess.get("id")+""));
				fprdto.setBiddingStatus("4");
				fprdto.setFailReson("因有其他用户出更高返利佣金获得产品承销权，该产品承销权已归属新用户");
				fprdto.setUpdateBy(dto.getUpdateBy());
				fprdto.setBiddingFailDate(System.currentTimeMillis()+"");//承销失败时间
				fpBiddingReceiptDao.updateBiddingReceipt(fprdto);
				// 发送消息      
				//您承销的产品(名称)因有用户出更高返佣比例获得产品承销权，该产品承销权已归属新用户，如有问题请拨打电话
				String cont=String.format("您承销的产品【%s】因有用户出更高返佣比例获得产品承销权，该产品承销权已归属新用户，如有问题请拨打电话%s", queryBiddingReceiptSuccess.get("pName"),tel);
				String title = "承销失效";
				faNotice.setTitle(title);
				faNotice.setContent(cont);
				String faId = String.valueOf(queryBiddingReceiptSuccess.get("uId"));
				faNotice.setFaId(faId);
				faNoticeService.addFaNotice(faNotice);
				//发送短信
				try {
					messageSmsDTO.setFpSmsRecivePhoneNo(queryBiddingReceiptSuccess.get("uMobile")+"");
					messageSmsDTO.setFpSmsContent(cont);
					messageSmsDaoImpl.addMessageSms(messageSmsDTO);
				} catch (Exception e) {
					log.error("承销失效短信发送失败",e);
				}
				//极光推送
				jpushUserPhone(cont, title, faId);
			}
			// 给当前承销人发送消息
			//您竞价的产品“+名称+“已审核成功，您已获取产品承销权，如有问题请拨打电话400-855-8085
			String value=String.format("您竞价的产品【%s】已审核成功，您已获取产品承销权，如有问题请拨打电话%s", currentBidding.get("pName"),tel);
			String title = "承销成功";
			faNotice.setTitle(title);
			faNotice.setContent(value);
			String faId=String.valueOf(currentBidding.get("uId"));
			faNotice.setFaId(faId);
			faNoticeService.addFaNotice(faNotice);
			//发送短信承销成功
			try {
				messageSmsDTO.setFpSmsRecivePhoneNo(loginName);
				messageSmsDTO.setFpSmsContent(value);
				messageSmsDaoImpl.addMessageSms(messageSmsDTO);
			} catch (Exception e) {
				log.error(title,e);
			}
			//极光推送
			jpushUserPhone(value, title, faId);
		}
	 
	   //竞价状态1，提交竞价，2、竞价失败3，成功,
	   boolean flagCheck=BiddingReceiptEnums.BIDDING_STATUS_CG.equalsIgnoreCase(biddingStatus)
			   ||BiddingReceiptEnums.BIDDING_STATUS_SB.equalsIgnoreCase(biddingStatus);
	   //4 承销失效5放弃承销，6、收回承销
	   boolean flagFail= BiddingReceiptEnums.BIDDING_STATUS_SX.equalsIgnoreCase(biddingStatus)
			   ||BiddingReceiptEnums.BIDDING_STATUS_SH.equalsIgnoreCase(biddingStatus)
			   ||BiddingReceiptEnums.BIDDING_STATUS_FQ.equalsIgnoreCase(biddingStatus);
	   if(flagCheck){
		   dto.setCheckDate(System.currentTimeMillis()+"");//设置审核时间
	   }else if(flagFail){
		   dto.setBiddingFailDate(System.currentTimeMillis()+"");//设置审核时间
	   }
	   
	   //更新审核状态
	   fpBiddingReceiptDao.updateBiddingReceipt(dto);
	   
	   //审核失败
		if(BiddingReceiptEnums.BIDDING_STATUS_SB.equalsIgnoreCase(biddingStatus)){
			// 承销成功短信  审核失败，
			log.info("承销成功短信  审核失败，");
			//您竞价的产品“+名称+”因为"+选择或其他原因+"审核失败，如有问题请拨打电话400-855-8085
			String s=String.format("您竞价的产品【%s】因为%s审核失败，如有问题请拨打电话%s", currentBidding.get("pName"),dto.getFailReson(),tel);
			String title="承销失败";
			faNotice.setTitle(title);
			faNotice.setContent(s);
			String faId=String.valueOf(currentBidding.get("uId"));
			faNotice.setFaId(faId);
			faNoticeService.addFaNotice(faNotice);
			//发送短信承销成功短信  审核失败，
			try {
				messageSmsDTO.setFpSmsRecivePhoneNo(loginName);
				messageSmsDTO.setFpSmsContent(s);
				messageSmsDaoImpl.addMessageSms(messageSmsDTO);
			} catch (Exception e) {
				log.error("承销成功短信  审核失败，",e);
			}
			//极光推送
			jpushUserPhone(s, title, faId);
		}
		//收回承销权
		else if(BiddingReceiptEnums.BIDDING_STATUS_SH.equalsIgnoreCase(biddingStatus)){
			// 承销失败短信  收回承销权，竞价失效，    
			//您承销的产品“+名称+”因为"+选择或其他原因+"被收回承销权，如有问题请拨打电话400-855-8085
			log.info("收回承销权");
			String s=String.format("您承销的产品【%s】因为%s被收回承销权，如有问题请拨打电话%s", currentBidding.get("pName"),dto.getFailReson(),tel);
			String title = "收回承销";
			faNotice.setTitle(title);
			faNotice.setContent(s);
			String faId=String.valueOf(currentBidding.get("uId"));
			faNotice.setFaId(faId);
			faNoticeService.addFaNotice(faNotice);
			//发送短信收回承销权
			try {
				messageSmsDTO.setFpSmsRecivePhoneNo(loginName);
				messageSmsDTO.setFpSmsContent(s);
				messageSmsDaoImpl.addMessageSms(messageSmsDTO);
			} catch (Exception e) {
				log.error("收回承销权",e);
			}
			//极光推送
			jpushUserPhone(s, title, faId);
		}
		
		return 0;
	}
	
	/***
	 * 
	
	* @Title: jpushUserPhone
	
	* @Description: 极光推送消息
	
	* @param @param cont
	* @param @param title
	* @param @param faId
	* @param @throws SQLException    设定文件
	
	* @return void    返回类型
	
	* @throws
	 */
	public void jpushUserPhone(String cont, String title, String faId)
			throws SQLException {
		// 根据用户查询出绑定的设备标示
		List<MessageJpushUserPhoneAliasDTO> phoneAlias = jpushMessageDaoImpl.queryJpushUserPhonealias(faId);
		if(null != phoneAlias && phoneAlias.size() >= 1){
			MessageJpushDTO messageJpushDTO = new MessageJpushDTO();
			for (MessageJpushUserPhoneAliasDTO messageJpushUserPhoneAliasDTO : phoneAlias) {
				messageJpushDTO.setFpJpushMsgRec(messageJpushUserPhoneAliasDTO.getFpJpushAlias());
				messageJpushDTO.setFpJpushTitle(title);
				messageJpushDTO.setFpJpushContent(cont);
				
				messageJpushDTO.setFpJpushRedrict(new String(Base64.encode(URLEncoder.encode(jpushRedrict).getBytes())));
				
				messageJpushDTO.setFpJpushMsgType("01");// 消息类型 01:系统消息 02:运营推送
				messageJpushDTO.setFpJpushSendType("01");// 推送消息类型  01:实时推送  02:定时推送
				messageJpushDTO.setCreateBy(faId + "");
				messageJpushDTO.setCreateDate(new Date());
				messageJpushDTO.setUpdateBy(faId + "");
				messageJpushDTO.setUpdateDate(new Date());
				jpushMessageDaoImpl.addJpushMessage(messageJpushDTO);
			}
		}
	}
	
	
	@Override
	@Transactional(rollbackFor=Exception.class)
	public Integer addFpBiddingReceiptBatch(JSONArray jsonArray,FpBiddingReceiptDTO fpBiddingReceiptDto) throws Exception {
		FpBiddingReceiptDTO fbrd=new FpBiddingReceiptDTO();
		// 初始化属性
		fbrd.setSrouce(fpBiddingReceiptDto.getSrouce());//来自 pc还是手机
		if("true".equals(fpBiddingReceiptDto.getFlagAnonymous())){
			fpBiddingReceiptDto.setFlagAnonymous(BiddingReceiptEnums.FLAG_BAIL_NO);
		}else if("false".equals(fpBiddingReceiptDto.getFlagAnonymous())){
			fpBiddingReceiptDto.setFlagAnonymous(BiddingReceiptEnums.FLAG_BAIL_YES);
		}else{
			fpBiddingReceiptDto.setFlagAnonymous(BiddingReceiptEnums.FLAG_BAIL_NO);
		}
		fbrd.setFlagAnonymous(fpBiddingReceiptDto.getFlagAnonymous());//是否匿名
		fbrd.setFlagBail(BiddingReceiptEnums.FLAG_BAIL_YES);//默认未交保证金
		fbrd.setBiddingStatus(BiddingReceiptEnums.BIDDING_STATUS_CG);//默认为竞价成功
		fbrd.setFaId(fpBiddingReceiptDto.getFaId());
		fbrd.setpId(fpBiddingReceiptDto.getpId());
		fbrd.setBiddingCode(SequenceManagerNew.seq_bzj());//竞价code   保证金支付使用
		//计算保证金金额
		fbrd.setBailAmount(new BigDecimal(0));
		fbrd.setUpdateBy(fpBiddingReceiptDto.getUpdateBy());
		fbrd.setCreateBy(fpBiddingReceiptDto.getCreateBy());
		//新增竞价
		int biddingReceiptId=fpBiddingReceiptDao.addFpBiddingReceipt(fbrd);
		//新增  竞价佣金
		FpBiddingRevenueDTO revenueDto=new FpBiddingRevenueDTO();
		revenueDto.setReceiptId(biddingReceiptId);
		revenueDto.setUpdateBy(fpBiddingReceiptDto.getUpdateBy());
		revenueDto.setCreateBy(fpBiddingReceiptDto.getCreateBy());
		// 初始化属性
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject object = jsonArray.getJSONObject(i);
			Integer id = object.getInt("id");//佣金id
			BigDecimal rebate = new BigDecimal(object.get("rebate")+"");//竞价返佣
			revenueDto.setAnnualRevenueId(id);
			revenueDto.setpRebateAmount(rebate);
			fpBiddingReceiptDao.addFpBiddingRevenue(revenueDto);
		}
		
		
		FaNoticeDTO faNotice=new FaNoticeDTO();
		faNotice.setCreateBy(fpBiddingReceiptDto.getUpdateBy());
		faNotice.setUpdateBy(fpBiddingReceiptDto.getUpdateBy());
		faNotice.setType("09");//消息通知
		faNotice.setProductId(fpBiddingReceiptDto.getpId());
		faNotice.setProductType(fpBiddingReceiptDto.getpType());
		faNotice.setSource("【SuperFA】");
		faNotice.setStatus("01");
		//您竞价的产品“+名称+”因为"+选择或其他原因+"审核失败，如有问题请拨打电话400-855-8085
		String content=String.format("您竞价的产品【%s】已审核成功，您已获取产品承销权，如有问题请拨打电话%s", fpBiddingReceiptDto.getpName(),tel);
		faNotice.setTitle("承销成功");
		faNotice.setContent(content);
		faNotice.setFaId(fpBiddingReceiptDto.getFaId());
		faNoticeService.addFaNotice(faNotice);
		
		//发送短信
		try {
			MessageSmsDTO messageSmsDTO=new MessageSmsDTO();
			//添加短信息
			messageSmsDTO.setCreateBy(fpBiddingReceiptDto.getUpdateBy());
			messageSmsDTO.setUpdateBy(fpBiddingReceiptDto.getUpdateBy());
			messageSmsDTO.setCreateDate(new Date());
			messageSmsDTO.setUpdateDate(new Date());
			messageSmsDTO.setFpSmsContent(content);
			messageSmsDTO.setFpSmsSendType(Dict.message_type_now);
			messageSmsDTO.setStatus(Dict.status_normal);
			messageSmsDTO.setFpSmsType("smsSendSwitch");
			messageSmsDTO.setFpSmsSendStatus(Dict.message_status_not_send);
			messageSmsDTO.setFpSmsRecivePhoneNo(fpBiddingReceiptDto.getMobile());
			messageSmsDaoImpl.addMessageSms(messageSmsDTO);
		} catch (Exception e) {
			log.error("承销成功短信发送失败",e);
		}
		
		return biddingReceiptId;
	}


	@Override
	public Map<String, Object> queryBiddingReceiptSuccess(
			FpBiddingReceiptDTO dto) throws SQLException {
		return fpBiddingReceiptDao.queryBiddingReceiptSuccess(dto);
	}

	@Override
	public List<Map<String, Object>> queryBiddingReceiptSuccessRebate(
			FpBiddingReceiptDTO dto) throws SQLException {
		return fpBiddingReceiptDao.queryBiddingReceiptSuccessRebate(dto);
	}
	@Override
	public List<Map<String, Object>> queryUnFreezingBailList(
			FpBiddingReceiptDTO dto) throws SQLException {
		return fpBiddingReceiptDao.queryUnFreezingBailList(dto);
	}
	@Override
	public FpBiddingReceiptDTO queryBiddingReceipt(FpBiddingReceiptDTO dto)
			throws SQLException {
		return fpBiddingReceiptDao.queryBiddingReceipt(dto);
	}
}
